﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;

namespace Project
{
	/// <summary>
	/// Interaction logic for App.xaml
	/// </summary>
	public partial class App : Application
	{
		[DllImport("user32.dll")]
	private static extern bool ShowWindow(IntPtr hWnd, int cmdShow);
	private const int SW_MAXIMIZE = 3;
	private const int SW_SHOWNORMAL = 1;

	private static Mutex singleInstanceMutex = new Mutex(true, "AnyUniqueStringToYourApp");

	protected override void OnStartup(StartupEventArgs e) {
		base.OnStartup(e);
		if (singleInstanceMutex.WaitOne(TimeSpan.Zero, true))
			base.OnStartup(e);
		else {
			var procs = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);
			foreach (var p in procs.Where(p => p.MainWindowHandle != IntPtr.Zero)) {
                ShowWindow(p.MainWindowHandle, SW_SHOWNORMAL);
					Application.Current.Shutdown();
					return;
				}
			}	
		}
	}
}
